package com.yangming.springboot.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yangming.springboot.base.ResultInfo;
import com.yangming.springboot.dao.UserDao;
import com.yangming.springboot.dao.UserRoleDao;
import com.yangming.springboot.model.UserModel;
import com.yangming.springboot.query.UserQuery;
import com.yangming.springboot.utils.AssertUtil;
import com.yangming.springboot.utils.Md5Util;
import com.yangming.springboot.utils.PhoneUtil;
import com.yangming.springboot.utils.UserIdBase64;
import com.yangming.springboot.vo.User;
import com.yangming.springboot.vo.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleDao userRoleDao;

    public UserModel login(String userName, String userPwd){
        checkLoginParams(userName, userPwd);
        User user = userDao.queryUserByUserName(userName);
        AssertUtil.isTrue(user == null, "user,error");
//        AssertUtil.isTrue(!(user.getUserPwd().equals(Md5Util.encode(userPwd))), "pwd,error"); //后台数据库存的是明文MD5密码，但是前段现在我自己做的没有没有MD5加密，所以拿来匹配，怎么都不会对的
        AssertUtil.isTrue(!(user.getUserPwd().equals(userPwd)), "pwd,error");
        return buildUserInfo(user);
    }

    private UserModel buildUserInfo(User user){
        UserModel userModel = new UserModel();
        userModel.setUserId(UserIdBase64.encodeUserID(user.getId()));
        userModel.setUserName(user.getUserName());
        userModel.setTrueName("ergou");
        return userModel;
    }

    private void checkLoginParams(String userName, String userPwd){
        AssertUtil.isTrue(userName == "", "name,error");
        AssertUtil.isTrue(userPwd == "", "pwd,error");
    }

    public void updateUserPassword(Integer userId, String oldPassword, String newPassword, String comfirmPassword){
        /*
         * 1.参数校验
         * id非空，新旧密码非空，旧密码与数据库的相同，
         * 新密码与旧密码不相同
         * 确认密码与新密码相同
         * 2.设置新密码，对密码进行加密处理
         * 3.执行跟新操作
         * */
        checkParams(userId, oldPassword, newPassword, comfirmPassword);
        User user = userDao.queryById(userId);
        user.setPwd(Md5Util.encode(newPassword));
        AssertUtil.isTrue(userDao.update(user)<1, "update error");
    }

    private void checkParams(Integer userId, String oldPassword, String newPassword, String comfirmPassword){
        User temp = userDao.queryById(userId);
        System.out.println(temp);
        AssertUtil.isTrue(userId == null || temp == null, "reset,error");
        AssertUtil.isTrue(oldPassword == "", "origin pwd, error");
        AssertUtil.isTrue(newPassword == "", "new pwd, error");
        AssertUtil.isTrue(comfirmPassword == "", "confirmpwd, error");
        System.out.println(Md5Util.encode(oldPassword));
        AssertUtil.isTrue(!(temp.getUserPwd().equals(oldPassword)), "unequals with old password"); //原始密码没有Md5加密的，所以啥都匹配不上
//        AssertUtil.isTrue(!(temp.getUserPwd().equals(Md5Util.encode(oldPassword))), "unequals with old password");
        AssertUtil.isTrue(!(newPassword.equals(comfirmPassword)), "new unequals with old");
        AssertUtil.isTrue((oldPassword.equals(newPassword)), "old equals width comfirm");
    }

    public User queryUserByName(String name){
        return userDao.queryUserByUserName(name);
    }

    public User queryUserById(Integer id){
        return userDao.queryById(id);
    }

    public void saveUser(User user){
        checkFormParams(user.getUserName(), user.getEmail(), user.getPhone());
        user.setIsValid(1);
        user.setCreateDate(new Date());
        user.setUpdateDate(new Date());
        userDao.save(user);

        //获取用户ID
        Integer userId = userDao.queryUserByUserName(user.getUserName()).getId();
        String roleId = user.getRoleId();
        //添加用户角色记录到用户角色表
        AssertUtil.isTrue(roleId == null, "roleid error");
        relationUserRoles(userId, roleId);
    }

    private void checkFormParams(String userName, String email, String phone){
        AssertUtil.isTrue(userName == null || userName == "", "username error");
        AssertUtil.isTrue(email == null || email == "", "email error");
        AssertUtil.isTrue(!PhoneUtil.isMobile(phone), "phone format error");
        AssertUtil.isTrue(userDao.queryUserByUserName(userName) != null, "username repeat");
    }
    /**
     * 批量用户角色关联
     * */
    private void relationUserRoles(Integer userId, String roleId){
        int total = userRoleDao.countUserRoleByUserId(userId);
        if (total > 0){
            //先把用户原有的角色关联全部删除，然后在去添加新的，这样不管是新增操作还是更新操作都可以使用这个逻辑
            AssertUtil.isTrue(userRoleDao.deleteUserRoleByUserId(userId) != total, "userrole delete failuren");
        }

        //这里写的是批量添加
        AssertUtil.isTrue(roleId == null, "roleid empty");
        List<UserRole> userRoles = new ArrayList<UserRole>();
        if (roleId != null){
            for(String s : roleId.split(",")){
                UserRole userRole = new UserRole();
                userRole.setCreateDate(new Date());
                userRole.setRoleId(Integer.parseInt(s));
                userRole.setUpdateDate(new Date());
                userRole.setUserId(userId);
                userRoles.add(userRole);
            }
        }
        userRoleDao.insertBatch(userRoles);
    }



    public void update(User user){
        User temp = userDao.queryById(user.getId());
        AssertUtil.isTrue(temp == null, "user disappear");
        checkFromParams(user.getUserName(), user.getEmail(), user.getPhone());
        temp = userDao.queryUserByUserName(user.getUserName());
        AssertUtil.isTrue(temp == null && !temp.getId().equals(user.getId()), "用户存在");
        user.setUpdateDate(new Date());
        userDao.update(user);

        /**
         * 添加用户角色表
         * 用户修改时，原始角色记录
         * 存在
         *  删除原来的全部，重新添加
         *  找到原来存在的进行匹配，加入新的
         *  直接添加用户角色记录，但是容易造成重复
         * 不存在
         *  直接批量添加用户角色记录
         * 第三种方案
         *  删除原有用户角色记录-》加入修改后的用户角色记录，整挺好
         * */
        relationUserRoles(user.getId(), user.getRoleId());

    }

    private void checkFromParams(String userName, String email, String phone){
        AssertUtil.isTrue(userName == null, "user name empty");
        AssertUtil.isTrue(email == null, "user email empty");
        AssertUtil.isTrue(phone == null, "user phone empty");
    }

    public void deleteUser(Integer[] ids){
        AssertUtil.isTrue(ids == null || ids.length == 0, "user id empty");
        userDao.deleteBatch(ids);
    }

//    public PageInfo<User> queryUserByParams(UserQuery userQuery){
//        PageHelper.startPage(userQuery.getPageNum(), userQuery.getPageSize());
//        List<User> users = userDao.selectByParams(userQuery);
//        return new PageInfo<User>(Users);
//    }

    public List<Map<String, Object>> queryAllSale(){
        return userDao.queryAllSales();
    }

    public Map<String, Object> queryUserByParams(UserQuery userQuery){
        Map<String, Object> map = new HashMap<String, Object>();
        PageHelper.startPage(userQuery.getPage(), userQuery.getLimit());
        PageInfo<User> pageInfo = new PageInfo<User>(userDao.selectByUserParams(userQuery));
        map.put("code", 0);
        map.put("msg","");
        map.put("count",pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }

}
